package com.ray.controller.base;

import com.ray.log.WebLog;
import com.ray.model.DataTask;
import com.ray.util.Ret;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 定时任务处理类
 */
@RestController
@RequestMapping("/quartz")
public class QuartzController extends BaseController {

    @Autowired
    private Scheduler scheduler;

    /**
     * @note 启动任务
     * @time 2024年03月25日 10:39:39
     * @author Ray
     */
    @RequestMapping("start")
    @WebLog(description = "启动任务")
    public Ret start(@RequestBody DataTask task) throws SchedulerException {
        String className = task.getStr("clazz");
        // 恢复任务
        JobKey jobKey = JobKey.jobKey(className, className);
        scheduler.resumeJob(jobKey);
        dbService.update(base, "data_task", "update data_task set state = '" + DataTask.STATE_START + "' where id = " + task.getId());
        return Ret.ok("msg", "启动成功");
    }

    /**
     * @note 暂停任务
     * @time 2024年03月25日 10:40:54
     * @author Ray
     */
    @RequestMapping("stop")
    @WebLog(description = "暂停任务")
    public Ret stop(@RequestBody DataTask task) throws SchedulerException {
        String className = task.getStr("clazz");
        // 暂停任务
        JobKey jobKey = JobKey.jobKey(className, className);
        scheduler.pauseJob(jobKey);
        dbService.update(base, "data_task", "update data_task set state = '" + DataTask.STATE_STOP + "' where id = " + task.getId());
        //Db.use(base).update("update data_task set state = ? where id = ?", DataTask.STATE_STOP, task.getId());
        return Ret.ok("msg", "停用任务成功");
    }

    /**
     * @note 立即执行一次任务
     * @time 2024年03月25日 10:41:40
     * @author Ray
     */
    @RequestMapping("trigger")
    @WebLog(description = "立即执行一次任务")
    public Ret trigger(@RequestBody DataTask task) throws SchedulerException {
        String className = task.getStr("clazz");
        // 立即触发
        JobKey jobKey = JobKey.jobKey(className, className);
        scheduler.triggerJob(jobKey);
        return Ret.ok("msg", "执行任务成功");
    }
}
